{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# cover_rectangle_sat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/examples/cover_rectangle_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/python/cover_rectangle_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "Fill a 60x50 rectangle by a minimum number of non-overlapping squares.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Sequence\n",
    "from ortools.sat.python import cp_model\n",
    "\n",
    "\n",
    "def cover_rectangle(num_squares: int) -> bool:\n",
    "    \"\"\"Try to fill the rectangle with a given number of squares.\"\"\"\n",
    "    size_x = 60\n",
    "    size_y = 50\n",
    "\n",
    "    model = cp_model.CpModel()\n",
    "\n",
    "    areas = []\n",
    "    sizes = []\n",
    "    x_intervals = []\n",
    "    y_intervals = []\n",
    "    x_starts = []\n",
    "    y_starts = []\n",
    "\n",
    "    # Creates intervals for the NoOverlap2D and size variables.\n",
    "    for i in range(num_squares):\n",
    "        size = model.new_int_var(1, size_y, \"size_%i\" % i)\n",
    "        start_x = model.new_int_var(0, size_x, \"sx_%i\" % i)\n",
    "        end_x = model.new_int_var(0, size_x, \"ex_%i\" % i)\n",
    "        start_y = model.new_int_var(0, size_y, \"sy_%i\" % i)\n",
    "        end_y = model.new_int_var(0, size_y, \"ey_%i\" % i)\n",
    "\n",
    "        interval_x = model.new_interval_var(start_x, size, end_x, \"ix_%i\" % i)\n",
    "        interval_y = model.new_interval_var(start_y, size, end_y, \"iy_%i\" % i)\n",
    "\n",
    "        area = model.new_int_var(1, size_y * size_y, \"area_%i\" % i)\n",
    "        model.add_multiplication_equality(area, [size, size])\n",
    "\n",
    "        areas.append(area)\n",
    "        x_intervals.append(interval_x)\n",
    "        y_intervals.append(interval_y)\n",
    "        sizes.append(size)\n",
    "        x_starts.append(start_x)\n",
    "        y_starts.append(start_y)\n",
    "\n",
    "    # Main constraint.\n",
    "    model.add_no_overlap_2d(x_intervals, y_intervals)\n",
    "\n",
    "    # Redundant constraints.\n",
    "    model.add_cumulative(x_intervals, sizes, size_y)\n",
    "    model.add_cumulative(y_intervals, sizes, size_x)\n",
    "\n",
    "    # Forces the rectangle to be exactly covered.\n",
    "    model.add(sum(areas) == size_x * size_y)\n",
    "\n",
    "    # Symmetry breaking 1: sizes are ordered.\n",
    "    for i in range(num_squares - 1):\n",
    "        model.add(sizes[i] <= sizes[i + 1])\n",
    "\n",
    "        # Define same to be true iff sizes[i] == sizes[i + 1]\n",
    "        same = model.new_bool_var(\"\")\n",
    "        model.add(sizes[i] == sizes[i + 1]).only_enforce_if(same)\n",
    "        model.add(sizes[i] < sizes[i + 1]).only_enforce_if(~same)\n",
    "\n",
    "        # Tie break with starts.\n",
    "        model.add(x_starts[i] <= x_starts[i + 1]).only_enforce_if(same)\n",
    "\n",
    "    # Symmetry breaking 2: first square in one quadrant.\n",
    "    model.add(x_starts[0] < (size_x + 1) // 2)\n",
    "    model.add(y_starts[0] < (size_y + 1) // 2)\n",
    "\n",
    "    # Creates a solver and solves.\n",
    "    solver = cp_model.CpSolver()\n",
    "    solver.parameters.num_workers = 8\n",
    "    solver.parameters.max_time_in_seconds = 10.0\n",
    "    status = solver.solve(model)\n",
    "    print(\"%s found in %0.2fs\" % (solver.status_name(status), solver.wall_time))\n",
    "\n",
    "    # Prints solution.\n",
    "    solution_found = status == cp_model.OPTIMAL or status == cp_model.FEASIBLE\n",
    "    if solution_found:\n",
    "        display = [[\" \" for _ in range(size_x)] for _ in range(size_y)]\n",
    "        for i in range(num_squares):\n",
    "            sol_x = solver.value(x_starts[i])\n",
    "            sol_y = solver.value(y_starts[i])\n",
    "            sol_s = solver.value(sizes[i])\n",
    "            char = format(i, \"01x\")\n",
    "            for j in range(sol_s):\n",
    "                for k in range(sol_s):\n",
    "                    if display[sol_y + j][sol_x + k] != \" \":\n",
    "                        print(\n",
    "                            \"ERROR between %s and %s\"\n",
    "                            % (display[sol_y + j][sol_x + k], char)\n",
    "                        )\n",
    "                    display[sol_y + j][sol_x + k] = char\n",
    "\n",
    "        for line in range(size_y):\n",
    "            print(\" \".join(display[line]))\n",
    "    return solution_found\n",
    "\n",
    "\n",
    "def main(argv: Sequence[str]) -> None:\n",
    "    if len(argv) > 1:\n",
    "        raise app.UsageError(\"Too many command-line arguments.\")\n",
    "    for num_squares in range(1, 15):\n",
    "        print(\"Trying with size =\", num_squares)\n",
    "        if cover_rectangle(num_squares):\n",
    "            break\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
